Component({
  externalClasses: ['i-class'],
  options: {
    multipleSlots: true
  },
  properties: {
    backgroundColor: {
      type: String,
      value: ''
    },
    firstTop: {
      type: Number,
      value: 0,
      observer: function(newVal, oldVal) {
        this.data.currTop = newVal;
        this.setData({
          currTop: newVal
        });
      }
    }
  },
  relations: {
    '../sticky/index': {
      type: 'parent'
    }
  },
  data: {
    top: 0,
    currTop: 0,
    height: 0,
    headHeight: 0,
    isSticky: true,
    isFixed: false,
    index: -1
  },
  methods: {
    updateScrollTopChange(scrollTop) {
      if (!this.data.isSticky)
        return;

      const data = this.data;
      const top = data.top;
      const height = data.height;

      const firstTop = data.firstTop;
      const headHeight = data.headHeight;
      let currTop = firstTop;
      let isFixed = (scrollTop >= top && scrollTop < top + height);
      let overlap = scrollTop - (top + height - headHeight);
      if (overlap > 0) {
        if (overlap < headHeight) {
          currTop = firstTop - overlap;
        } else {
          currTop = firstTop - height;
        }
      }
      this.setData({
        currTop: currTop,
        isFixed: isFixed
      })
    },
    updateDataChange(index) {
      const navBarInfo = getApp().globalData.navBarInfo;
      if (!navBarInfo || navBarInfo.system.indexOf('iOS') > -1) {
        this.setData({
          isSticky: false
        });
      }
      const className = '.i-sticky-item';
      const query = wx.createSelectorQuery().in(this);
      query.select(className).boundingClientRect((res) => {
        if (res) {
          let isFixed = this.data.isFixed;
          const isSticky = this.data.isSticky;
          if (isSticky) {
            if (index == 0) {
              const firstTop = this.data.firstTop;
              isFixed = (res.top >= firstTop && res.top < firstTop + res.height);
            }
          }
          this.setData({
            top: res.top - this.data.firstTop,
            height: res.height,
            isFixed: isFixed,
            index: index
          });
        }
      }).exec();
      const headClassName = '.i-sticky-item-header';
      query.select(headClassName).boundingClientRect((res) => {
        if (res) {
          this.setData({
            headHeight: res.height
          });
        }
      }).exec();
    }
  }
})